use std::str::FromStr;

use crate::convert::{IntoResponse, FromBody};
use crate::http::HttpContentType;

pub struct Text<T>(pub T);

impl<T: ToString> IntoResponse for Text<T> {
    fn status_code(&self) -> u16 {
        200 
    }

    fn content_type(&self) -> HttpContentType {
        HttpContentType::TextPlain
    }

    fn into_body(self) -> Vec<u8> {
        self.0.to_string().into_bytes()
    }
}

impl<T> FromBody for Text<T>
where 
    T: FromStr,
    T::Err: std::error::Error + 'static,
{
    type Err = Box<dyn std::error::Error>;
    fn from_body(bytes: Vec<u8>) -> Result<Self, Self::Err> {
        let s = str::from_utf8(&bytes)?;
        let val = <T as FromStr>::from_str(s)?;
        Ok(Text(val))
    }
}